import { ForbiddenException, Injectable } from '@nestjs/common';
import { CreateMajorDto } from './dto/create-major.dto';
import { UpdateMajorDto } from './dto/update-major.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Major } from './entities/major.entity';
import { Repository } from 'typeorm';

@Injectable()
export class MajorService {
  constructor(
    @InjectRepository(Major)
    private majorRepository: Repository<Major>,
  ) {}

  async create(createDepartmentDto: CreateMajorDto) {
    const res = await this.majorRepository.create(createDepartmentDto);
    return await this.majorRepository.save(res);
  }

  findAll() {
    return this.majorRepository.find({ relations: ['department'] });
  }

  findOne(id: number) {
    return this.majorRepository.findOne({
      where: { id },
      relations: ['department'],
    });
  }

  async update(id: number, updateDepartmentDto: UpdateMajorDto) {
    const findRes = await this.findOne(id);
    if (!findRes?.id) {
      throw new ForbiddenException('专业不存在');
    }
    delete findRes.department;
    const newDto = this.majorRepository.merge(findRes, updateDepartmentDto);
    return this.majorRepository.save(newDto);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    if (res?.id) {
      return await this.majorRepository.remove(res);
    }
    throw new ForbiddenException('专业不存在');
  }
}
